/*
 * GNU GENERAL PUBLIC LICENSE v2
 * 
 * Developers: Alan Audette, Oguz Bastemur
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Text; 
using Microsoft.SqlServer.Management.Common;
using System.Reflection;
using SqlDatabaseBackup.Helper;
using SqlDatabaseBackup.Tools;
using smo = Microsoft.SqlServer.Management.Smo;

namespace SqlDatabaseBackup
{ 
    class Program
    {
        /// <summary>
        /// Manager class to handle configuration settings
        /// </summary>
        internal static Configuration.ConfigurationManager configuration;

        /// <summary>
        /// List of .bak files created by the process
        /// </summary>
        internal static ArrayList OutputFiles = new ArrayList();


        /// <summary>
        /// Application entry point
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            ToConsole.GreenText("SQLDatabaseBackup version " + AssemblyHelper.ApplicationVersion);
            ToConsole.WriteLine();//NewLine

            // Populate the configuration manager
            configuration = Configuration.ConfigurationManager.GetConfiguration();  

            // Backup the databases
            if (!Backup.ProcessBackup())
                goto final;

            // Archive the backup files
            Backup.ArchiveFiles();

            //Delete Old Backups
            Backup.DeleteFiles();

        final:
            // Write out a spacer line
            ToConsole.WriteLine();

            if (!processFailed)
                Log.Message("SqlDatabaseBackup process completed", EventLogEntryType.SuccessAudit);
            else
                Log.Message("SqlDatabaseBackup process failed", EventLogEntryType.Warning);

            Mail.SendEmail();

            // Ask the user to confirm the results only if configured to do so
            if (configuration.UserInput.Require.ToLower() == "true")
            {
                if (processFailed)
                    ToConsole.RedText("Processing failed, press the Enter key to continue");
                else
                    // Tell the user that processing is complete
                    ToConsole.GreenText("Processing complete, press the Enter key to continue");

                // Wait for the user to confirm
                Console.ReadLine();
            }

            if (processFailed)
                Environment.Exit(1); // Process Failed
        }

        internal static bool processFailed = false;
    }
}
